<template>
  <a-modal
    width="50vw"
    unmount-on-close
    :mask-closable="false"
    :visible="visible"
    :title="form.id ? '修改账号及车辆' : '添加账号及车辆'"
    @cancel="handleCancel"
    @open="handleOpen"
    @before-ok="handleBeforeOk"
    @close="handleClose"
  >
    <page-form :model="form" layout="vertical" :rules="rules" ref="formRef">
      <page-form-row :gutter="24">
        <page-form-item field="accountEpName" label="企业名称" required size="1/2">
          <template v-if="form.status != 1">
            <a-input placeholder="请输入" allow-clear v-model="form.accountEpName" max-length="50" />
          </template>
          <template v-else>
            <div>{{ form.accountEpName }}</div>
          </template>
        </page-form-item>
        <page-form-item field="socialCreditNo" label="统一社会信用代码" required size="1/2">
          <template v-if="form.status != 1">
            <a-input placeholder="请输入" allow-clear v-model="form.socialCreditNo" max-length="50" />
          </template>
          <template v-else>
            <div>{{ form.socialCreditNo }}</div>
          </template>
        </page-form-item>
        <page-form-item v-if="form.status == 1" label="企业账号">
          <div>{{ form.account }}</div>
        </page-form-item>
        <page-form-item field="queryTime" label="查询违章时间" required size="1">
          <template v-if="form.status != 1">
            从<i-date-picker style="margin: 0 6px" v-model="form.queryTime" :disabled-date="disablequeryTime" />
            后查询违章
          </template>
          <template v-else>
            <div> 从{{ queryTimeShow }}后查询违章 </div>
          </template>
        </page-form-item>
        <page-form-item field="carIdList" label="关联车辆" labelTooltipContent="关联车辆为所选企业在交管网站中存在的车辆" required size="1">
          <fast-transfer style="width: 100%" v-model="form.carIdList" :selectedList="selectedList" :data-source="roleData" />
        </page-form-item>
      </page-form-row>
    </page-form>
  </a-modal>
</template>

<script setup lang="ts">
  import { addViolationQuery, getViolationQueryCarList, getViolationQueryCarCount } from '@/api/asset/carViolation'
  import { Message } from '@arco-design/web-vue'
  import dayjs from 'dayjs'

  import { computed, ref } from 'vue'

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    options: {
      type: Object,
      default: () => ({}),
    },
  })
  const emits = defineEmits(['update:visible', 'onBeforeOk', 'close'])

  const visible = computed({
    get: () => props.visible,
    set: (val: boolean) => emits('update:visible', val),
  })

  // 不能选今天之后的时间
  const disablequeryTime = (currentDate: Date | undefined) => {
    const now = dayjs()
    const dateToCheck = dayjs(currentDate)

    // 检查 currentDate 是否有效
    if (!dateToCheck.isValid()) {
      console.error('Invalid date:', currentDate)
      return false
    }

    return dateToCheck.isAfter(now, 'day')
  }

  // 查询违章时间转换成 x年x月x日
  const queryTimeShow = computed(() => {
    return dayjs(form.value.queryTime).format('YYYY年M月D日')
  })

  const form = ref<any>({})
  const rules = ref<any>({
    accountEpName: [{ required: true, message: '请输入企业名称' }],
    socialCreditNo: [{ required: true, message: '请输入统一社会信用代码' }],
    carIdList: [{ required: true, message: '请选择关联车辆' }],
    queryTime: [{ required: true, message: '请选择查询违章时间' }],
  })
  const formRef = ref<any>(null)
  const roleData = ref<any[]>([])
  const selectedList = ref<any[]>([])

  // 获取所有关联车辆
  const violationQueryCarList = async (id?: string | number) => {
    const res = await getViolationQueryCarList({ id })
    roleData.value = res.result.map((item: any) => {
      return {
        label: item.licenseNo,
        value: item.id,
      }
    })
  }

  // 获取当前账户的关联车辆
  const loadCarList = () => {
    getViolationQueryCarCount({ accountId: props.options.id, pageNumber: 1 }).then((res: any) => {
      form.value.carIdList = res.result.data.map((item: any) => item.carId)
      selectedList.value = []
    })
  }

  const handleOpen = () => {
    console.log('props.options', props.options)

    // status: 0 未开通 1 已开通 2 开通失败
    form.value = {
      id: props.options?.id,
      accountEpName: props.options?.accountEpName,
      socialCreditNo: props.options?.socialCreditNo,
      account: props.options?.account,
      status: props.options?.status,
      queryTime: props.options?.queryTime ?? '2024-01-01',
    }

    violationQueryCarList(props.options?.id).then(() => {
      if (props.options?.id) {
        loadCarList()
      }
    })
  }

  const handleBeforeOk = (done: (closed: boolean) => void) => {
    formRef.value.validate((valid: boolean) => {
      if (!valid) {
        addViolationQuery(form.value)
          .then(() => {
            if (props.options?.id) {
              Message.success('修改成功')
            } else {
              Message.success('添加成功')
            }

            visible.value = false
            emits('onBeforeOk')
            done(true)
          })
          .catch((err: any) => {
            console.log('err', err)
            done(false)
          })
      } else {
        done(false)
      }
    })
  }

  const handleCancel = () => {
    visible.value = false
  }

  const handleClose = () => {
    selectedList.value = []
    roleData.value = []
    formRef.value.resetFields()
    emits('close')
  }
</script>

<style scoped lang="less"></style>
